<template>
  <div style="width: calc(100% - 10px);">
    <div class="form-title">
      <el-date-picker
          v-model="nowYear"
          type="year"
          change="loadHoliday"
          value-format="YYYY"
          :editable="false"
          :clearable="false"
          size="large"
        />
        <el-button type="primary" round style="margin-left:20px;" @click="handleClickInit">初始化</el-button>
    </div>
    <el-row :gutter="20" v-for="index of 4" :key="index">
      <el-col :span="8" v-for="item of 3" :key="item">
        <el-calendar
        :model-value="new Date(nowYear, (index-1)*3+item-1)"
        >
          <template #header="{ date }">
            <span>{{ date }}</span>
          </template>
          <template #date-cell="{ data }">
            <!-- click.stop防止点击事件向上传播，切换月份 -->
            <div :class="showHoliday(data)" style=" height:100%;width:100%;cursor: pointer;" @click.stop="clickDay(data)">
              {{ data.day.split('-').slice(2).join('-') }}
            </div>
          </template>
        </el-calendar>
      </el-col>
    </el-row>
  </div>
</template>
<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { loadHolidayByYear, setHoliday, initHolidayByYear } from '@/api/system/holiday/HolidayManager'
const nowYear = ref('')
const holidayList = ref([])

const showHoliday = computed(() => (data) => {
  return holidayList.value.indexOf(data.day) > -1 ? 'red' : ''
})

const clickDay = (data) => {
  setHoliday(data.day).then(() => {
    if (holidayList.value.indexOf(data.day) > -1) {
      holidayList.value.splice(holidayList.value.indexOf(data.day), 1)
    } else {
      holidayList.value.push(data.day)
    }
  }).catch(() => {
    ElMessage.error('设置失败！')
  })
}

onMounted(() => {
  nowYear.value = new Date().getFullYear().toString()

  loadHoliday()
})

const loadHoliday = () => {
  loadHolidayByYear(nowYear.value).then((data) => {
    holidayList.value = data
  }).catch(() => {
    ElMessage.error('数据加载失败！')
  })
}

const handleClickInit = () => {
  ElMessageBox.confirm('是否初始化？初始化将删除本年度设置')
    .then(() => {
      initHolidayByYear(nowYear.value).then((data) => {
        if (data) {
          ElMessage.success('初始化成功。')
          loadHoliday()
        } else {
          ElMessage.error('初始化失败！')
        }
      }).catch(() => {
        ElMessage.error('初始化失败！')
      })
    })
    .catch(() => {
      // catch error
    })
}

</script>
<style lang="scss" scope>
.form-title{
  padding: 20px;
  text-align: center;
}

table thead{
  background: var(--el-border-color-lighter);
}

.prev, .next{
  pointer-events:none;
}

.red{
  color: red;
}
</style>
